/**
 *
 * Copyright 1991-2010 TEAM International. All rights reserved 
 *
 */
package com.lindenvalley.de;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lindenvalley.de.content.Answer;
import com.lindenvalley.de.content.Question;
import com.lindenvalley.de.content.Section;
import com.lindenvalley.de.database.DbSectionsHelper;
import com.lindenvalley.de.network.WorkServer;

/**
 * @author RuslanI
 *
 */
public class LearnActivity extends Activity {

	private final String TAG = getClass().getSimpleName();
	private int currentThemeId;
	private Section section;
	private List<Question> questions;
	private int questionSize;
	private TextView headerView, bodyView, nextView, nameView, currentQuestionLabelView;
	private int currentQuestion, countQuestion, NO_QUESTION = -1;
	private int currentRound = 1;
	private MyTouchListener listener;
	private Random random = new Random();
	private LinearLayout answerLayout, scrollLayout, correctAnswerLayout;
	private List<Integer> showedQuestionNumber;
	private ImageView scrollLeft, scrollRight;
	private HorizontalScrollView scrollView;
	private final int QUESTION_LABEL_ID = 1000;
	public static final int CORRENT_ANSWER = 1;
	public static final int INCORRECT_ANSWER = 0;
	public static final int NOT_ANSWER = -1;
	private DbSectionsHelper sectionsHelper;
	private SQLiteDatabase sectionsWriteDatabase, sectionsReadDatabase;
	private String[] columns = new String[]{"max(" + DbSectionsHelper.ROUND + ")", "count(" + DbSectionsHelper.ANSWER_TYPE + ")" };
	private boolean isExamMode;
	private static final long EXAM_TIMEOUT = 5400000;
	private long examLeft, startExamTime;
	private Handler handler;
	private EndOfExamTask examTask;
	private StringBuilder answersResult;
	private static final String PREF_NAME = "MyPref";
	private SharedPreferences preferences;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
		preferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
		currentQuestion = NO_QUESTION;
		handler = new Handler();
		examTask = new EndOfExamTask();
		startExamTime = System.currentTimeMillis();
		currentThemeId = getIntent().getIntExtra(MainActivity.EXTRA_THEME_NUMBER, 0);
		isExamMode = getIntent().getBooleanExtra(MainActivity.EXTRA_EXAM_MODE, false);
		sectionsHelper = new DbSectionsHelper(this);
		sectionsReadDatabase = sectionsHelper.getReadableDatabase();
		answersResult = new StringBuilder();

		setContentView(R.layout.learn);
		if (showedQuestionNumber == null){
			showedQuestionNumber = new LinkedList<Integer>();
		}
		//TODO Сделать для екзамена выбор рандомных вопросов 25% от всех существующих во всех темах
		if (currentThemeId > 0 && !isExamMode){
			section = WorkServer.getInstance().getSections().getSectionById(currentThemeId);
			questions = section.getQuestion();
		} 
		else {
			//TODO Берем общее колличество вопросов и от него 25% будем пользовать выборочно
			List<Question> allQuestions = WorkServer.getInstance().getSections().getAllQuestion();
			int allSize = allQuestions.size();
			int size = allSize / 4;
			
			section = new Section();
			section.setQuestion(new ArrayList<Question>());
			for(int i = 0; i < size; i++){
				Question q = null;
				do {
					int nextQuestionId = random.nextInt(allSize-1);
					q = allQuestions.get(nextQuestionId);
				} while (section.getQuestion().contains(q));
				section.getQuestion().add(q);
			}
			
		}
		
		//Находим все раунды по нашей теме
		String selection = DbSectionsHelper.THEME_ID + "=? and " + DbSectionsHelper.IS_EXAM + "=?";
		String[] whereArgs = new String[]{
				String.valueOf(currentThemeId),
				(isExamMode? "1" : "0")};
		Cursor cursor = sectionsReadDatabase.query(DbSectionsHelper.TABLE_NAME, columns, selection, whereArgs, DbSectionsHelper.ROUND, null, DbSectionsHelper.ROUND + " desc");
		cursor.moveToFirst();
		try{
			currentRound = cursor.getInt(0);
			int countQuestion = cursor.getInt(1);
			if (countQuestion >= questions.size()){
				currentRound += 1;
			} else {
				Cursor cursorSections = sectionsReadDatabase.query(
						DbSectionsHelper.TABLE_NAME,
						new String[] { DbSectionsHelper.QUESTION },
						DbSectionsHelper.THEME_ID + "=? and " + DbSectionsHelper.ROUND + "=? and " + DbSectionsHelper.IS_EXAM + "=?",
						new String[] { String.valueOf(currentThemeId),String.valueOf(currentRound), (isExamMode? "1" : "0") }, null, null,
						null);
				if (cursorSections.getCount() > 0) {
					cursorSections.moveToFirst();
					showedQuestionNumber = new LinkedList<Integer>();
					do {
						int value = cursorSections.getInt(0);
						showedQuestionNumber.add(value);
					} while (cursorSections.moveToNext());
					cursorSections.close();
				}
				
			}
		} catch (CursorIndexOutOfBoundsException ex){
			
		}
		sectionsReadDatabase.close();
		
		// колличество оставшихся вопросов
		questionSize = questions.size() - showedQuestionNumber.size();

		listener = new MyTouchListener();
		headerView = (TextView)findViewById(R.id.questionHeader);
		bodyView = (TextView)findViewById(R.id.questionBody);
		nextView = (TextView)findViewById(R.id.questionBtnNext);
		nameView = (TextView)findViewById(R.id.questionName);
		answerLayout = (LinearLayout)findViewById(R.id.questionAnswerLayout);
		scrollLayout = (LinearLayout)findViewById(R.id.questionLinearLayout2);
		correctAnswerLayout = (LinearLayout)findViewById(R.id.questionRightAnswerLayout);
		scrollView = (HorizontalScrollView)findViewById(R.id.scrollView1);
		scrollLeft = (ImageView)findViewById(R.id.questionScrollLeft);
		scrollRight = (ImageView)findViewById(R.id.questionScrollRight);
		scrollLeft.setOnTouchListener(listener);
		scrollRight.setOnTouchListener(listener);
		Section section = WorkServer.getInstance().getSections().getSectionById(currentThemeId);
		nameView.setText(section.getName());
		
		if (questions != null && questions.size() > 0){
			nextView.setOnTouchListener(listener);
			if (!isExamMode)
				currentQuestion = preferences.getInt(String.valueOf(currentThemeId), -1);
			showQuestion(currentQuestion);
		}		
		
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		Log.i(TAG, " void onResume()....");
		super.onResume();
		sectionsWriteDatabase = sectionsHelper.getWritableDatabase();
		handler.postDelayed(examTask, EXAM_TIMEOUT-examLeft);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		Log.i(TAG, " void onStop()....");
		super.onStop();
		handler.removeCallbacks(examTask);
		examLeft = System.currentTimeMillis() - startExamTime;
		
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		Log.i(TAG, " void onPause()....");
		super.onPause();
		sectionsWriteDatabase.close();
		if (!isExamMode && countQuestion == questionSize){
			Editor editor = preferences.edit();
			editor.remove(String.valueOf(currentThemeId));
			editor.commit();
		} else if (!isExamMode && countQuestion < questionSize){
			SharedPreferences.Editor editor = preferences.edit();
			editor.putInt(String.valueOf(currentThemeId), currentQuestion);
			editor.commit();

		}
	}

	/**
	 * Appear next question if param is -1. If index >=0 appear index element of array 
	 * @param index index value of array questions,
	 */
	private void showQuestion(int index){
		if (correctAnswerLayout.getVisibility() == View.VISIBLE){
			correctAnswerLayout.setVisibility(View.GONE);
		}
		if (currentQuestionLabelView != null)
			currentQuestionLabelView.setBackgroundResource(0);
		if (countQuestion < questionSize || index >= 0){
			Question question = null;
			if (index < 0){
				do{
					currentQuestion = random.nextInt(questions.size());				
				} while (showedQuestionNumber.contains(currentQuestion));
				showedQuestionNumber.add(currentQuestion);
			} else{
				currentQuestion = index;
			}
			
			question = questions.get(currentQuestion);		
			
			if (question != null && question.isFillQuestion()){
				headerView.setText(question.getTitle());
				Spanned spannedText = Html.fromHtml(question.getDescription());
				bodyView.setText(spannedText);
				answerLayout.removeAllViews();
				List<Answer> answers = question.getAnswer();
				if (Question.RESPONSE_TYPE_ORDINARY.equals(question.getResponseType())){
					if (answers != null){
						RadioGroup group = new RadioGroup(this);
						group.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
						group.setTag("RadioGroup");
						answerLayout.addView(group);
						for(Answer answer: answers){
							RadioButton box = new RadioButton(this);
							box.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
							box.setText(answer.getDescription());
							box.setTextSize(11);
							box.setTag(Integer.valueOf(answer.getId()));
							box.setTextColor(Color.BLACK);
							box.setBackgroundResource(R.drawable.question_btn);
							box.setId(Integer.valueOf(answer.getId()));
							group.addView(box);
						}
					}
				} else if (Question.RESPONSE_TYPE_MULTY.equals(question.getResponseType())){
					if (answers != null){
						for(Answer answer: answers){
							CheckBox box = new CheckBox(this);
							box.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
							box.setText(answer.getDescription());
							box.setTextSize(11);
							box.setTag(Integer.valueOf(answer.getId()));
							box.setTextColor(Color.BLACK);
							box.setBackgroundResource(R.drawable.question_btn);
							box.setId(Integer.valueOf(answer.getId()));
							answerLayout.addView(box);
						}
					}
				} else if (Question.RESPONSE_TYPE_TEXT.equals(question.getResponseType())){
					if (answers != null){
						for(Answer answer: answers){
							EditText box = new EditText(this);
							box.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));							
							box.setTag(Integer.valueOf(answer.getId()));
							box.setGravity(Gravity.NO_GRAVITY);
							answerLayout.addView(box);
						}
					}
				}
				currentQuestionLabelView = (TextView) scrollLayout.findViewWithTag(Integer.valueOf(currentQuestion));
				if (currentQuestionLabelView == null){
					currentQuestionLabelView = new TextView(this);
					currentQuestionLabelView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
					currentQuestionLabelView.setGravity(Gravity.CENTER);
					currentQuestionLabelView.setTextColor(Color.BLACK);
					currentQuestionLabelView.setPadding(10, 0, 10, 0);
					currentQuestionLabelView.setText(countQuestion+1 + "");
					currentQuestionLabelView.setOnTouchListener(listener);
					currentQuestionLabelView.setId(QUESTION_LABEL_ID);
					currentQuestionLabelView.setTag(Integer.valueOf(currentQuestion));
					currentQuestionLabelView.setBackgroundResource(R.drawable.question_curr_questtion);
					scrollLayout.addView(currentQuestionLabelView);
				} else {
//					currentQuestionLabelView = (TextView) scrollLayout.findViewWithTag(Integer.valueOf(currentQuestion));
					currentQuestionLabelView.setBackgroundResource(R.drawable.question_curr_questtion);
				}
			}
			if (index < 0 || countQuestion == 0)
				countQuestion++;
		} else {
			if (isExamMode){
				Intent intent = new Intent(this, ReportActivity.class);
				intent.putExtra(MainActivity.EXTRA_THEME_NUMBER, currentThemeId);
				intent.putExtra(MainActivity.EXTRA_ROUND_NUMBER, currentRound);
				startActivity(intent);
			}
			finish();
		}
		
	}
	
	/**
	 * Check answer. Answers checks when user is learning
	 * @return 1 - connect answer. -1 - incorrect answer. 0 - skiped answer
	 */
	private int checkAnswer(){
		
		int answerResult = NOT_ANSWER;
//		if (isExamMode)
//			return CORRENT_ANSWER;
		
		if (correctAnswerLayout.getVisibility() == View.VISIBLE){
			correctAnswerLayout.setVisibility(View.GONE);
			return answerResult;
		}
		TextView tv = (TextView) scrollLayout.findViewWithTag(Integer.valueOf(currentQuestion));
		Question question = questions.get(currentQuestion);
		List<Answer> answers = question.getRightAnswers();
		if (question.isFillQuestion()){
			// проверка для responseType = ORDINARY
			if (Question.RESPONSE_TYPE_ORDINARY.equals(question.getResponseType())){
				Answer rightAnswer = answers.get(0);
				RadioGroup group = (RadioGroup)answerLayout.findViewWithTag("RadioGroup");
				int chechedButton = group.getCheckedRadioButtonId();
				answersResult.append(String.valueOf(chechedButton));
				if (chechedButton == rightAnswer.getId()){
					answerResult = CORRENT_ANSWER;					
				} else if (chechedButton != rightAnswer.getId() && chechedButton >=0){
					answerResult = INCORRECT_ANSWER;
					if (!isExamMode){
						RadioButton correctButton = (RadioButton)group.findViewById(rightAnswer.getId());
						RadioButton incorrectButton = (RadioButton)group.findViewById(chechedButton);
						correctButton.setBackgroundResource(R.drawable.question_bg_correct);
						incorrectButton.setBackgroundResource(R.drawable.question_bg_incorrect);
					}
				}
				
			// проверка для responseType = MULTI
			} else if (Question.RESPONSE_TYPE_MULTY.equals(question.getResponseType())){
				boolean rightResult = false;			
				for (Answer a: answers){
					CheckBox checkBox = (CheckBox)answerLayout.findViewById(Integer.valueOf(a.getId()));
					if (checkBox.isChecked())
						rightResult = true;
					else 
						rightResult = false;
						
				}
				boolean isChecked = false;
				for (int i = 0; i< answerLayout.getChildCount(); i++ ){
					CheckBox box = (CheckBox)answerLayout.getChildAt(i);
					if (box.isChecked()){
						isChecked = box.isChecked();
						if (answersResult.length() > 0)
							answersResult.append(',');
						answersResult.append(String.valueOf(box.getId()));
					}
				}
				
				if (rightResult){
					answerResult = CORRENT_ANSWER;
				} else if (!rightResult && isChecked){
					answerResult = INCORRECT_ANSWER;
					
					if (!isExamMode){
						for (Answer a: answers){
							for (int i = 0; i< answerLayout.getChildCount(); i++ ){
								CheckBox box = (CheckBox)answerLayout.getChildAt(i);
								if (box.isChecked() && box.getId() == a.getId()){
									box.setBackgroundResource(R.drawable.question_bg_correct);
								} else if (box.isChecked() && box.getId() != a.getId()){
									box.setBackgroundResource(R.drawable.question_bg_incorrect);
								} else {
									box.setBackgroundResource(R.drawable.question_bg_skip);
								}
							}
						}
					}
				}
				//TODO Доделать проверку текста
			// проверка для responseType = TEXT				
			} else if (Question.RESPONSE_TYPE_TEXT.equals(question.getResponseType())){
				
			}
			if (!isExamMode){
				switch (answerResult) {
				case CORRENT_ANSWER:
					tv.setTextColor(getResources().getColor(R.color.colorAnswerGreen));
					break;
				case INCORRECT_ANSWER:
					tv.setTextColor(getResources().getColor(R.color.colorAnswerRed));
					correctAnswerLayout.setVisibility(View.VISIBLE);
					ScrollView scroll = (ScrollView) findViewById(R.id.scrollView2);
					scroll.pageScroll(View.FOCUS_DOWN);
					break;
				case NOT_ANSWER:
					tv.setTextColor(getResources().getColor(R.color.colorAnswerYellow));
					break;
				}
			}
			writeAnswerToDatabase(currentQuestion, answerResult);
		}
		return answerResult;
		
	}
	
	/**
	 * Wtite answer to database. If there is not answer, current round will close
	 * @param question
	 * @param answer
	 */
	private void writeAnswerToDatabase(int question, int answer){
		ContentValues values = new ContentValues();		
		values.put(DbSectionsHelper.ANSWER_TYPE, answer);
		values.put(DbSectionsHelper.ANSWERS, answersResult.toString());
		if (showedQuestionNumber.contains(Integer.valueOf(question)) && showedQuestionNumber.indexOf(Integer.valueOf(question)) != showedQuestionNumber.size()-1){
			String whereClause = DbSectionsHelper.THEME_ID + "=? and " + DbSectionsHelper.ROUND + "=? and " + DbSectionsHelper.QUESTION + "=?";
			String[] whereArgs = new String[]{String.valueOf(currentThemeId), String.valueOf(currentRound), String.valueOf(question)}; 
			sectionsWriteDatabase.update(DbSectionsHelper.TABLE_NAME, values, whereClause, whereArgs);
		} else {
			values.put(DbSectionsHelper.THEME_ID, currentThemeId);
			values.put(DbSectionsHelper.ROUND, currentRound);
			values.put(DbSectionsHelper.QUESTION, question);
			if (isExamMode)
				values.put(DbSectionsHelper.IS_EXAM, 1);
			else
				values.put(DbSectionsHelper.IS_EXAM, 0);
			sectionsWriteDatabase.insert(DbSectionsHelper.TABLE_NAME, null, values);
		}
		answersResult.setLength(0);
//		answersResult.trimToSize();
		
//		if (countQuestion == questionSize){
//			SQLiteDatabase roundDatabase = roundsHelper.getWritableDatabase();
//			values.clear();
//			values.put(DbRoundsHelper.IS_OPEN, 0);
//			String[] whereArgs = new String[]{String.valueOf(currentThemeId), String.valueOf(currentRound)};
//			roundDatabase.update(DbRoundsHelper.TABLE_NAME, values, DbRoundsHelper.THEME_ID + "=? and " + DbRoundsHelper.CURR_ROUND + "=?", whereArgs);
//			roundDatabase.close();
//		}
	}
	
	

	class MyTouchListener implements View.OnTouchListener{

		/* (non-Javadoc)
		 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
		 */
		@Override
		public boolean onTouch(View v, MotionEvent event) {

			int id = v.getId();
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				switch (id) {
				case R.id.questionBtnNext:
					if (checkAnswer() != INCORRECT_ANSWER || isExamMode)
						showQuestion(-1);
					break;
				case R.id.questionScrollLeft:
					scrollView.pageScroll(View.FOCUS_LEFT);
					break;
				case R.id.questionScrollRight:
					scrollView.pageScroll(View.FOCUS_RIGHT);
					break;
				case QUESTION_LABEL_ID:
					Integer index = (Integer) v.getTag();
					checkAnswer();
					showQuestion(index);
					break;
				}
				return true;
			} else
				return false;
		}
		
	}
	
	class EndOfExamTask implements Runnable{

		/* (non-Javadoc)
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			Log.i(TAG, "Running End of task....");
			if (!LearnActivity.this.isFinishing()){
				LearnActivity.this.finish();
				
			}
		}
		
	}

}
